""" 
光敏传感器
功能说明: https://blog.csdn.net/weixin_58632615/article/details/124729997
接线:
    DO --> gpio26 : 
        低光照, DO输出高电平
        高强度光照, DO输出低电平
    AO --> gpio34 :
        adc 值,0~1023
    VCC --> 5V
    GND --> GND
    
实验现象:
    低光照时, ao_adc 4055, do_pin 输出高电平, led 熄灭
    高光照时, ao_adc 2065, do_pin 输出低电平, led 点亮
"""

from machine import Pin, ADC
import time

DO_PIN_NUM = 2  # 光敏传感器DO 输入
AO_PIN_NUM = 34  # 光敏传感器AO 输入
LED_PIN_NUM = 15  # LED端口
Do_Trigger_Type = 0  # 触发值/条件
count = 0

do_pin = None
ao_adc = None
led_pin = None


def irq_call_back(irq_pin):
    global count
    global led_pin
    global Do_Trigger_Type

    value = irq_pin.value()
    if value == Do_Trigger_Type:
        led_pin.value(1)
        print(f"高光照 +++ {count}")
    else:
        led_pin.value(0)
        print(f"低光照 --- {count}")
    count += 1


def init_setup():
    global DO_PIN_NUM, AO_PIN_NUM, LED_PIN_NUM
    global do_pin, ao_adc, led_pin
    global Do_Trigger_Type

    # 1.初始化D0
    """1.input 低电平触发,上升沿"""
    Pin_Pull_Type = Pin.PULL_DOWN
    irq_trigger_type = Pin.IRQ_RISING
    if Do_Trigger_Type == 0:
        """2.input 高电平触发,下降沿"""
        irq_trigger_type = Pin.IRQ_FALLING
        Pin_Pull_Type = Pin.PULL_UP
    do_pin = Pin(DO_PIN_NUM, Pin.IN, Pin_Pull_Type)
    do_pin.irq(trigger=irq_trigger_type, handler=irq_call_back)
    # 2.初始化led
    led_pin = Pin(LED_PIN_NUM, Pin.OUT)  # 输出
    led_pin.value(0)

    # 3.初始化ADC
    ao_adc = ADC(Pin(AO_PIN_NUM))
    ao_adc.atten(ADC.ATTN_11DB)  # 设置衰减为11db,范围0~3.6v


def loop_run():
    global ao_adc
    while True:
        value = ao_adc.read()
        print(f"ADC值: {value}")
        time.sleep(1)


# 程序入口
if __name__ == "__main__":
    init_setup()
    loop_run()
